package com.formaplus.appcom14.utilitiares;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

public class ImageManager {

	
	private String _mPath;
	public ImageManager(){
		
		_mPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/imagesAppCom14";
		File lImagesFolder=new File(_mPath);
		
		if(!lImagesFolder.exists())
			lImagesFolder.mkdirs();
	}

	public Bitmap getImageFromServer(String url){

		Bitmap myBitmap=null;
		/**
		 * Afficher une imge depuis une URL
		 */
		URL myImageURL;
		try {
			myImageURL = new URL(url);

			HttpURLConnection connection = (HttpURLConnection) myImageURL.openConnection();
			connection.setDoInput(true);
			connection.connect();
			InputStream input = connection.getInputStream();

			myBitmap = BitmapFactory.decodeStream(input);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return myBitmap;
	}
	
	public void downloadImageToSdcard(String pUrl,String pImageName){

    	/**
    	 * SAUVGARDER une imge depuis une URL
    	 */
    	OutputStream fOut = null;

    	File f=new File(_mPath, pImageName+".png");

    	if(!f.exists()){
    		try {
    			fOut = new FileOutputStream(f);

    			Bitmap lBitMap=getImageFromServer(pUrl);

    			if(lBitMap!=null){
    				lBitMap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    				fOut.flush();
    				fOut.close();
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
	
	public  Bitmap getImageFromSdCard(String pImageName) {
		Bitmap d = null ;
		try {

			// afficher l image de l emplacement X avec le nom pImageName
			d = BitmapFactory.decodeFile(_mPath + "/" + pImageName+ ".png");

		} catch (IllegalArgumentException e) {
		}
		return d;

	}
}
